package init.luoyu.easymonitor.base.mybatis;


import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import init.luoyu.easymonitor.base.utils.CommonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * @author LuoYu
 * 2021/4/10
 **/
public class CodeGenerator {


    private static Logger logger = LoggerFactory.getLogger(CodeGenerator.class);

    private static final String jdbc_url = "jdbc:mysql://127.0.0.1:3306/luoyu_monitor1?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8";
    public static String username = "root";
    public static String password = "root";


    private static final String createTemplate = "baseCreate";
    private static final String updateTemplate = "baseUpdate";
    private static final String detailTemplate = "baseDetail";



    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + "：");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotEmpty(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "！");
    }
    public static void main(String[] args) {
            generatorDao();
    }



    public static void generatorDao(){
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();
        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor("LuoYu");
        gc.setOpen(false);
        mpg.setGlobalConfig(gc);
        // 数据源配置
//        String dbName = scanner("数据库名称");
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(jdbc_url);
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername(username);
        dsc.setPassword(password);
        mpg.setDataSource(dsc);
        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(scanner("模块名"));
        pc.setParent("init.luoyu.easymonitor.server");
        pc.setEntity("repository.model");
        pc.setMapper("repository.mapper");
        pc.setService("repository.service");
        pc.setServiceImpl("repository.service.impl");
        mpg.setPackageInfo(pc);
        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };
        // 如果模板引擎是 freemarker
        // 如果模板引擎是 velocity
        // String templatePath = "/templates/mapper.xml.vm";
        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
                return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });


        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);
        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();
        templateConfig.setEntity("templates/model/entity.java");
        templateConfig.setController("");
        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);
        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
//        strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        // 公共父类
//        strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
        // 写于父类中的公共字段
//        strategy.setSuperEntityColumns("id");
        strategy.setInclude(scanner("表名，多个英文逗号分割").split(","));
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }



    private static void generatorBusinessModel(String templateName,String modelName,String entityPre,String entitySif,String... tables){


        // 代码生成器
        logger.info("准备生成业务层代码....");
        AutoGenerator mpg = new AutoGenerator();
        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        logger.info("项目路径 ----> ProjectPath:{}",projectPath);
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor("LuoYu");
        gc.setOpen(false);
        String modelFullName = "";
        if(!CommonUtil.isEmptyStr(entityPre)) {
            modelFullName = entityPre.concat("%s");
        }
        if(!CommonUtil.isEmptyStr(entitySif)) {
            modelFullName = "%s".concat(entitySif);
        }
        gc.setEntityName(modelFullName);
        mpg.setGlobalConfig(gc);
        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(jdbc_url);
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername(username);
        dsc.setPassword(password);
        mpg.setDataSource(dsc);
        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(modelName);
        pc.setParent("init.luoyu.easymonitor.server");
        pc.setEntity("business.model.base");
        mpg.setPackageInfo(pc);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();
        //不生成如下类型模板
        templateConfig.setController(null);
        templateConfig.setService(null);
        templateConfig.setServiceImpl(null);
        templateConfig.setMapper(null);
        templateConfig.setXml(null);
        String templatePath = String.format("/templates/model/%s.java", templateName);
        templateConfig.setEntity(templatePath);
        logger.info("生成模块路径 ----> TemplatePath:{}",templatePath);
        mpg.setTemplate(templateConfig);
        // 配置模板
        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        strategy.setInclude(tables);
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        logger.debug("配置完毕 ----> 开始生成代码");
        mpg.execute();



    }











   public static void generatorBusiness(){
       // 代码生成器
       String modelName = scanner("模块名");
       String tableName = scanner("表名");
       generatorBusinessModel(createTemplate,modelName,"Create",null,tableName);
       generatorBusinessModel(updateTemplate,modelName,"Update",null,tableName);

   }











}
